﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Whoever.Framework.Utils;
using Whoever.Framework.Enum;

using Whoever.Patterns.MVC.Models;
using Whoever.Patterns.MVC.Filters;

using Comswing.Business.Core;
using Comswing.Business.Entities;
using Comswing.Website.Models.AccountViewModels;
using Comswing.Website.Infrastructure;

namespace Comswing.Website.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Index()
        {
            return View(new AccountViewModel());
        }

        [ActionName("Login")]
        [HttpPost]
        [AJAXExceptionHandler]
        public ActionResult LoginPost(LoginViewModel login)
        {
            if (ModelState.IsValid)
            {
                SessionState.LoggedInUser = null;

                var user = ManagerFactory.UserManager.Login(new User { Account = login.Account, Password = login.Password });
                if (user.IsLoggedin)
                {
                    SessionState.LoggedInUser = user;
                    return Json(new AJAXResponse { Success = true, MustRedirect = true, RedirectURL = Url.Action("Index", "Swing") });
                }
            }
            throw new Exception(Localized.Message("Model", MessageType.Error));
        }

        [AJAXExceptionHandler]
        public ActionResult Logout()
        {
            ManagerFactory.UserManager.Logout(SessionState.LoggedInUser);
            SessionState.LoggedInUser = null;
            return View("Index");
        }
    }
}
